package com.mjk.common.util;


/*
 *   
 */
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符转换类
 * 
 * @author csx
 * 
 */
public class StringUtil {

	/**
	 * 判断某个字符串是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		if (StringUtil.isEmpty(str)) {
			return false;
		}
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 简单的字符串格式化，性能较好。支持不多于10个占位符，从%1开始计算，数目可变。参数类型可以是字符串、Integer、Object，
	 * 甚至int等基本类型
	 * 、以及null，但只是简单的调用toString()，较复杂的情况用String.format()。每个参数可以在表达式出现多次。
	 * 
	 * @param msgWithFormat
	 * @param autoQuote
	 * @param args
	 * @return
	 */
	public static StringBuilder formatMsg(CharSequence msgWithFormat,
			boolean autoQuote, Object... args) {
		int argsLen = args.length;
		boolean markFound = false;

		StringBuilder sb = new StringBuilder(msgWithFormat);

		if (argsLen > 0) {
			for (int i = 0; i < argsLen; i++) {
				String flag = "%" + (i + 1);
				int idx = sb.indexOf(flag);
				// 支持多次出现、替换的代码
				while (idx >= 0) {
					markFound = true;
					sb.replace(idx, idx + 2, toString(args[i], autoQuote));
					idx = sb.indexOf(flag);
				}
			}

			if (args[argsLen - 1] instanceof Throwable) {
				StringWriter sw = new StringWriter();
				((Throwable) args[argsLen - 1])
						.printStackTrace(new PrintWriter(sw));
				sb.append("\n").append(sw.toString());
			} else if (argsLen == 1 && !markFound) {
				sb.append(args[argsLen - 1].toString());
			}
		}
		return sb;
	}

	public static StringBuilder formatMsg(String msgWithFormat, Object... args) {
		return formatMsg(new StringBuilder(msgWithFormat), true, args);
	}

	public static String toString(Object obj, boolean autoQuote) {
		StringBuilder sb = new StringBuilder();
		if (obj == null) {
			sb.append("NULL");
		} else {
			if (obj instanceof Object[]) {
				for (int i = 0; i < ((Object[]) obj).length; i++) {
					sb.append(((Object[]) obj)[i]).append(", ");
				}
				if (sb.length() > 0) {
					sb.delete(sb.length() - 2, sb.length());
				}
			} else {
				sb.append(obj.toString());
			}
		}
		if (autoQuote
				&& sb.length() > 0
				&& !((sb.charAt(0) == '[' && sb.charAt(sb.length() - 1) == ']') || (sb
						.charAt(0) == '{' && sb.charAt(sb.length() - 1) == '}'))) {
			sb.insert(0, "[").append("]");
		}
		return sb.toString();
	}

	/**
	 * 把字符串中的带‘与"转成\'与\"
	 * 
	 * @param orgStr
	 * @return
	 */
	public static String convertQuot(String orgStr) {
		return orgStr.replace("'", "\\'").replace("\"", "\\\"");
	}

	/**
	 * 删除后面指定的字符
	 * 
	 * @param toTrim
	 * @param trimStr
	 * @return
	 */
	public static String trimSufffix(String toTrim, String trimStr) {
		
		if(StringUtil.isEmpty(toTrim))
		{
			return "";
		}
		while (toTrim.endsWith(trimStr)) {
			toTrim = toTrim.substring(0, toTrim.length() - trimStr.length());
		}
		return toTrim;
	}

	/**
	 * HTML实体编码转成普通的编码
	 * 
	 * @param dataStr
	 * @return
	 */
	public static String htmlEntityToString(final String dataStr) {
		int start = 0;
		int end = 0;
		final StringBuffer buffer = new StringBuffer();
		while (start > -1) {
			int system = 10;// 进制
			if (start == 0) {
				int t = dataStr.indexOf("&#");
				if (start != t)
					start = t;
			}
			end = dataStr.indexOf(";", start + 2);
			String charStr = "";
			if (end != -1) {
				charStr = dataStr.substring(start + 2, end);
				// 判断进制
				char s = charStr.charAt(0);
				if (s == 'x' || s == 'X') {
					system = 16;
					charStr = charStr.substring(1);
				}
			}
			// 转换
			try {
				char letter = (char) Integer.parseInt(charStr, system);
				buffer.append(new Character(letter).toString());
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}

			// 处理当前unicode字符到下一个unicode字符之间的非unicode字符
			start = dataStr.indexOf("&#", end);
			if (start - end > 1) {
				buffer.append(dataStr.substring(end + 1, start));
			}

			// 处理最后面的非unicode字符
			if (start == -1) {
				int length = dataStr.length();
				if (end + 1 != length) {
					buffer.append(dataStr.substring(end + 1, length));
				}
			}
		}
		return buffer.toString();
	}

	/**
	 * 把String转成html实体字符
	 * 
	 * @param str
	 * @return
	 */
	public static String stringToHtmlEntity(String str) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);

			switch (c) {
			case 0x0A:
				sb.append(c);
				break;

			case '<':
				sb.append("&lt;");
				break;

			case '>':
				sb.append("&gt;");
				break;

			case '&':
				sb.append("&amp;");
				break;

			case '\'':
				sb.append("&apos;");
				break;

			case '"':
				sb.append("&quot;");
				break;

			default:
				if ((c < ' ') || (c > 0x7E)) {
					sb.append("&#x");
					sb.append(Integer.toString(c, 16));
					sb.append(';');
				} else {
					sb.append(c);
				}
			}
		}
		return sb.toString();
	}

	/**
	 * String转unicode
	 * 
	 * @param s
	 *            字符串
	 * @return unicode 编码
	 */
	public static String stringToUnicode(String s) {
		String unicode = "";
		char[] charAry = new char[s.length()];
		for (int i = 0; i < charAry.length; i++) {
			charAry[i] = (char) s.charAt(i);
			unicode += "\\u" + Integer.toString(charAry[i], 16);
		}
		return unicode;
	}

	/**
	 * unicode转String
	 * 
	 * @param unicodeStr
	 *            unicode 编码
	 * @return 字符串
	 */
	public static String unicodeToString(String unicodeStr) {
		StringBuffer sb = new StringBuffer();
		String str[] = unicodeStr.toUpperCase().split("\\\\U");
		for (int i = 0; i < str.length; i++) {
			if (str[i].equals(""))
				continue;
			char c = (char) Integer.parseInt(str[i].trim(), 16);
			sb.append(c);
		}
		return sb.toString();
	}

	/**
	 * 含html 标签的字符串转String
	 * 
	 * @param inputString
	 * @return
	 */
	public static String html2Text(String inputString) {
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		java.util.regex.Pattern p_script, p_style, p_html;
		java.util.regex.Matcher m_script, m_style, m_html;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script>]*?>[\s\S]*?<\/script>
			// }
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style>]*?>[\s\S]*?<\/style>
			// }
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

			p_script = java.util.regex.Pattern.compile(regEx_script,
					java.util.regex.Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = java.util.regex.Pattern.compile(regEx_style,
					java.util.regex.Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = java.util.regex.Pattern.compile(regEx_html,
					java.util.regex.Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}

		return textStr;// 返回文本字符串
	}

	/**
	 * 判断字符串非空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * 判断字符串是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0 || str.trim().equals("")
				|| str.trim().equals("null");
	}

	/**
	 * 转换成小写
	 * 
	 * @param str
	 * @return
	 */
	public static String toLowerCase(String str) {
		return str == null ? null : str.toLowerCase();
	}

	/**
	 * 转换成大写
	 * 
	 * @param str
	 * @return
	 */
	public static String toUpperCase(String str) {
		return str == null ? null : str.toUpperCase();
	}

	/**
	 * 字符串 编码转换
	 * 
	 * @param str
	 *            字符串
	 * @param from
	 *            原來的編碼
	 * @param to
	 *            轉換后的編碼
	 * @return
	 */
	public static String encodingString(String str, String from, String to) {
		String result = str;
		try {
			result = new String(str.getBytes(from), to);
		} catch (Exception e) {
			result = str;
		}
		return result;
	}

	public static Long toLong(String str) {
		return null == str ? null : (str == "" ? null : (StringUtils
				.isNumeric(str) ? (Long.parseLong(str)) : null));
	}

	/**
	 * 
	 * 判断时间显示格式，如果没有时间 则显示为""
	 * 
	 * @param str
	 * @return
	 */
	public static String getLineStr(String str) {

		if (isEmpty(str)) {
			return "";
		} else {
			return str;
		}
	}

	/**
	 * 
	 * 判断考勤结果显示，如果没有 则显示为"异常"
	 * 
	 * @param str
	 * @return
	 */
	public static String getUnknowStr(String str) {
		if (isEmpty(str)) {
			return "";
		} else {
			return str;
		}
	}


	/**
	 * 把一个String数组用","连接成一个字符串。 例如传入new String[] { "aaa", "bbb", "ccc"
	 * }，则返回'aaa','bbb','ccc'。
	 * 
	 * @param strings
	 *            String数组
	 * @return 连接后的字符串
	 */
	public static String connect(Object[] strings) {
		if (strings.length < 1) {
			return "";
		}

		StringBuffer str = new StringBuffer();
		str.append("'").append(strings[0]).append("'");
		for (int i = 1; i < strings.length; i++) {
			
			String s = "'" + strings[i] + "'";			
			str.append(",").append(s);
		}

		return str.toString();
	}

	/**
	 * 把一个List中存放的String数组用","连接成一个字符串。 例如传入new ArrayList().add(new String[] {
	 * "aaa","ddd" }...),.add(new String[] { "bbb","ddd" }...)，则返回"aaa,bbb,ccc"。
	 * 
	 * @param list
	 *            List(String[])
	 * @return 连接后的字符串
	 */
	public static String connect(List<String[]> list) {
		StringBuffer str = new StringBuffer();

		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {

				String[] string = (String[]) list.get(i);
				str.append(string[0]).append(",");

			}

			return str.toString().substring(0, str.length() - 1);

		} else {
			return "";
		}

	}

	/**
	 * 把一个List中存放的String用","连接成一个字符串。 例如传入new
	 * ArrayList().add("aaa"),.add("bbb")...，则返回'aaa','bbb','ccc'。
	 * 
	 * @param list
	 *            List(String)
	 * @return 连接后的字符串
	 */
	public static String connect2(List list) {
		StringBuffer sb = new StringBuffer();

		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {

				String str = "'" + list.get(i) + "'";
				sb.append(str).append(",");
			}

			return sb.toString().substring(0, sb.length() - 1);

		} else {
			return "";
		}

	}
	
	/**
	 * 将Set<Object>集合 用"," 拼接
	 * @param set
	 * @return
	 */
	public static String connectSet(Set set) {
		StringBuffer sb = new StringBuffer();
        
		if (set != null && set.size() > 0) {
			
			for (Object o : set) {
				String str = "'" + o + "'";
				sb.append(str).append(",");
			}
			return sb.toString().substring(0, sb.length() - 1);

		} else {
			return "";
		}

	}

	/**
	 * 字符串切割
	 * 
	 * @param str
	 * @return
	 */
	public static String strCut(String str, int num) {

		if (str != null && str.length() > num) {
			return str.substring(0, num) + "...";
		}
		return str;
	}

	/**
	 * 
	 * 将指定字符串的从"ISO-8859-1"转换为"UTF-8"格式
	 * 
	 * @param output
	 * @return
	 */
	public static String decodex(String output) {
		try {
			return new String(output.getBytes("ISO-8859-1"), "UTF-8");
		} catch (Exception ex) {
			return "";
		}
	}

	/**
	 * 
	 * 将 格式为 M.d 格式变为 yyyy-MM-dd
	 * 
	 * @param str
	 * @param year
	 * @return
	 */
	public static String tranDateStr(String str, String year) {
		if (StringUtil.isEmpty(str))
			return null;
		String[] arr = str.split("\\-");
		int pointIndex = arr[0].indexOf(".");
		String m = arr[0].substring(0, pointIndex);
		String mm = m.length() == 1 ? ("0" + m) : m;
		String d = arr[0].substring(pointIndex + 1);
		String dd = d.length() == 1 ? ("0" + d) : d;
		return (year + "-" + mm + "-" + dd).substring(0, 10);

	}

	/**
	 * 
	 * 将yyyy-M-d 转换成 yyyy-MM-dd
	 * 
	 * @param date
	 * @return
	 */
	public static String tranYMDDateStr(String date) {
		if (StringUtil.isEmpty(date))
			return null;
		String[] arr = date.split("\\-");
		String mm = arr[1].length() == 1 ? ("0" + arr[1]) : arr[1];
		String dd = arr[2].length() == 1 ? ("0" + arr[2]) : arr[2];
		return (arr[0] + "-" + mm + "-" + dd);

	}

	/**
	 * 
	 * 将H:S:S 转换成 HH:MM:SS
	 * 
	 * @param date
	 * @return
	 */
	public static String tranHMSDateStr(String date) {
		if (StringUtil.isEmpty(date))
			return null;
		String[] arr = date.split("\\:");
		String hh = arr[0].length() == 1 ? ("0" + arr[0]) : arr[0];
		String mm = arr[1].length() == 1 ? ("0" + arr[1]) : arr[1];
		String ss = arr[2].length() == 1 ? ("0" + arr[2]) : arr[2];
		return (hh + ":" + mm + ":" + ss);

	}

	/**
	 * 
	 * 将 yyyyMMdd格式转变成yyyy-MM-dd
	 * 
	 * @param str
	 * @return
	 */
	public static String getDateStr(String str) {
		if (str.length() == 8) {
			return str.substring(0, 4) + "-" + str.substring(4, 6) + "-"
					+ str.substring(6, 8);

		} else {
			return null;
		}
	}

	// 阿拉伯数字转中文小写
	public static String num2CnLow(String si) {
		String[] aa = { "", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿" };
		String[] bb = { "一", "二", "三", "四", "五", "六", "七", "八", "九" };
		char[] ch = si.toCharArray();
		int maxindex = ch.length;
		// 字符的转换
		// 两位数的特殊转换
		if (maxindex == 2) {
			for (int i = maxindex - 1, j = 0; i >= 0; i--, j++) {
				if (ch[j] != 48) {
					if (j == 0 && ch[j] == 49) {
						return aa[i];
					} else {
						return bb[ch[j] - 49] + aa[i];
					}
				}
			}
			// 其他位数的特殊转换，使用的是int类型最大的位数为十亿
		} else {
			for (int i = maxindex - 1, j = 0; i >= 0; i--, j++) {
				if (ch[j] != 48) {
					return bb[ch[j] - 49] + aa[i];
				}
			}
		}
		return si;
	}

	/**
	 * 
	 * 将字符串中带*的字符串 替换为 新的字符
	 * 
	 * @param o
	 *            524047001646****
	 * @param n
	 *            1111
	 * @return
	 */
	public static String replaceSpot(String o, String n) {
		if (isNotEmpty(o) && isNotEmpty(n)) {
			int x = o.indexOf("*");
			if (x != -1) {
				o = o.substring(0, x) + n;
			}
		}
		return o;
	}

	/**
	 * 
	 * 验证字符串 是否是日期格式 yyyyMMdd
	 * 
	 * @param dateStr
	 * @return
	 */
	public static boolean validDate(String dateStr) {
		String eL = "[0-9]{4}[0-9]{2}[0-9]{2}";
		Pattern p = Pattern.compile(eL);
		Matcher m = p.matcher(dateStr);
		boolean dateFlag = m.matches();
		if (!dateFlag) {
			return false;
		}
		return true;
	}

//	public static String encodingFileName(String fileName) {
//		String returnFileName = "";
//		try {
//			returnFileName = URLEncoder.encode(fileName, "UTF-8");
//			returnFileName = StringUtils.replace(returnFileName, "+", "%20");
//			if (returnFileName.length() > 150) {
//				returnFileName = new String(fileName.getBytes("GB2312"),
//						"ISO8859-1");
//				returnFileName = StringUtils
//						.replace(returnFileName, " ", "%20");
//			}
//		} catch (UnsupportedEncodingException e) {
//			// e.printStackTrace();
//			// if (log.isWarnEnabled()) {
//			// log.info("Don't support this encoding ...");
//			// }
//		}
//		return returnFileName;
//	}

	/**
	 * 使用Map 按value排序
	 * 
	 * @param oriMap
	 * @return
	 */
	public Map<String, String> sortMapByValue(Map<String, String> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		Map<String, String> sortedMap = new LinkedHashMap<String, String>();
		List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
				oriMap.entrySet());
		Collections.sort(entryList, new MapValueComparator());

		Iterator<Map.Entry<String, String>> iter = entryList.iterator();
		Map.Entry<String, String> tmpEntry = null;
		while (iter.hasNext()) {
			tmpEntry = iter.next();
			sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}
		return sortedMap;
	}

	class MapValueComparator implements Comparator<Map.Entry<String, String>> {

		@Override
		public int compare(Entry<String, String> me1, Entry<String, String> me2) {

			return me1.getValue().compareTo(me2.getValue());
		}
	}

	/**
	 * 使用 Map按key进行排序
	 * 
	 * @param map
	 * @return
	 */
	public Map<String, String> sortMapByKey(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}

		Map<String, String> sortMap = new TreeMap<String, String>(
				new MapKeyComparator());

		sortMap.putAll(map);

		return sortMap;
	}

	class MapKeyComparator implements Comparator<String> {

		@Override
		public int compare(String str1, String str2) {

			return str1.compareTo(str2);
		}
	}

	/**
	 * 测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

//		Map<String, String> oldMap = new HashMap<String, String>();
//		oldMap.put("entryDay", "2015-10-02");
//		oldMap.put("leaveDay", "2015-10-31 18:00:00");
//		oldMap.put("employDay", "2015-10-02");
//
//		oldMap = new StringUtil().sortMapByValue(oldMap);
//		for (Object o : oldMap.keySet()) {
//			System.out.println("key=" + o + " value=" + oldMap.get(o));
//		}
      System.out.println( connect(new String[]{"a","b","c"}));
	}
}
